<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="模板编号">
                <a-input v-model="queryParam.templateKeyword" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="模板名称">
                <a-input v-model="queryParam.templateName" placeholder="" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="合同名称">
                  <a-input v-model="queryParam.contractName" placeholder="" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="上架状态">
                  <a-select v-model="queryParam.isUpShelf" placeholder="请选择">
                    <a-select-option value="0">未上架</a-select-option>
                    <a-select-option value="1">已上架</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="参数配置状态">
                  <a-select v-model="queryParam.isConfParams" placeholder="请选择">
                    <a-select-option value="0">未配置</a-select-option>
                    <a-select-option value="1">已配置</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="模板类型">
                  <a-select v-model="queryParam.templateType" placeholder="请选择">
                    <a-select-option value="1">客户合同</a-select-option>
                    <a-select-option value="2">配资合同</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>

            <a-col :md="!advanced ? 8 : 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator">
        <a-button
          type="primary"
          icon="api"
          @click="_syncTempStatus"
          v-if="btnsPurviewData.sys.isShow"
        >同步模板</a-button
        >
        <!-- <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
        </a-dropdown> -->
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="templateNo"
        :columns="columns"
        :data="loadData"
        :alert="false"
        showPagination="auto"
        listName="dataList"
        :scroll="{ x: 'calc(2000px + 100%)' }"
        v-if="btnsPurviewData.query.isShow"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="iconUrl" slot-scope="text">
          <img class="iconUrl" :src="text" alt="" v-if="text" />
        </span>
        <span slot="templateType" slot-scope="text">
          {{ text | templateTypeFilter }}
        </span>
        <span slot="contractType" slot-scope="text">
          {{ text | contractTypeFilter }}
        </span>
        <span slot="isSignSeq" slot-scope="text">
          {{ text | isSignSeqFilter }}
        </span>
        <span slot="isUpShelf" slot-scope="text">
          {{ text | isUpShelfFilter }}
        </span>
        <span slot="isConfParams" slot-scope="text">
          {{ text | isConfParamsFilter }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <span v-if="btnsPurviewData.modifyShelf.isShow">
              <a @click="handleChangeShelves(record)">{{ record.isUpShelf == 1 ? '下架' : '上架' }}</a>
              <a-divider type="vertical" />
            </span>
            <span v-if="btnsPurviewData.config.isShow">
              <a @click="_toConfigTemp(record)">配置模板</a>
              <a-divider type="vertical" />
            </span>
            <a @click="_editTemp(record)" v-if="btnsPurviewData.update.isShow">修改模板</a>
          </template>
        </span>
      </s-table>
      <create-form
        ref="createForm"
        :visible="visible"
        :loading="confirmLoading"
        :title="formTitle"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      >
      </create-form>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { BTNS_PURVIEW_MAP } from '@/store/mutation-types'
import storage from 'store'
import { STable, Ellipsis } from '@/components'
import { getContractTempList, editShelves, syncTempStatus, updateTemp } from '@/api/custContractManage'
import CreateForm from './modules/CreateTempForm'
const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' },
    align: 'center',
    fixed: 'left',
    width: 80
  },
  {
    title: '模板名称',
    dataIndex: 'templateName',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '模板编号',
    dataIndex: 'templateNo',
    customRender: (text) => text || '—',
    align: 'center'
  },

  {
    title: '合同名称',
    dataIndex: 'contractName',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '合同描述',
    dataIndex: 'contractDescribe',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '合同类型',
    dataIndex: 'contractType',
    scopedSlots: { customRender: 'contractType' },
    align: 'center'
  },
  {
    title: '模板类型',
    dataIndex: 'templateType',
    scopedSlots: { customRender: 'templateType' },
    align: 'center'
  },
  {
    title: '签字顺序',
    dataIndex: 'isSignSeq',
    scopedSlots: { customRender: 'isSignSeq' },
    align: 'center'
  },

  {
    title: '上架状态',
    dataIndex: 'isUpShelf',
    scopedSlots: { customRender: 'isUpShelf' },
    align: 'center'
  },
  {
    title: '参数配置状态',
    dataIndex: 'isConfParams',
    scopedSlots: { customRender: 'isConfParams' },
    align: 'center'
  },

  {
    title: '上架时间',
    dataIndex: 'upShelfTime',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '签约合同数',
    dataIndex: 'contractNums',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '模板图标',
    dataIndex: 'iconUrl',
    scopedSlots: { customRender: 'iconUrl' },
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '270px',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    fixed: 'right'
  }
]

const statusMap = {
  1: {
    status: 'processing',
    text: '启用'
  },
  2: {
    status: 'default',
    text: '冻结'
  }
}

const contractTypeMap = {
  11: { text: '企业商户对企业客户' },
  12: { text: '企业商户对自然人客户' },
  21: { text: '自然人商户对企业客户' },
  22: { text: '自然人商户对自然人客户' }
}

const templateTypeMap = {
  1: { text: '客户合同' },
  2: { text: '配资合同' }
}

const isUpShelfMap = {
  0: {
    text: '未上架'
  },
  1: {
    text: '已上架'
  }
}

const isSignSeqMap = {
  0: {
    text: '无序'
  },
  1: {
    text: '有序'
  }
}

const isConfParamsMap = {
  0: {
    text: '未配置'
  },
  1: {
    text: '已配置'
  }
}

export default {
  name: 'ContractTemplateList',
  components: {
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      btnsPurviewMap: storage.get(BTNS_PURVIEW_MAP),
      btnsPurviewData: {},
      // create model
      visible: false,
      freezeVisible: false,
      confirmLoading: false,
      formTitle: '修改模板',
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getContractTempList(requestParameters)
          .then((res) => {
            return res.result
          })
          .catch((e) => {})
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    },
    isUpShelfFilter (type) {
      return isUpShelfMap[type]?.text ?? '—'
    },
    isSignSeqFilter (type) {
      return isSignSeqMap[type]?.text ?? '—'
    },
    contractTypeFilter (type) {
      return contractTypeMap[type]?.text ?? '—'
    },
    templateTypeFilter (type) {
      return templateTypeMap[type]?.text ?? '—'
    },
    isConfParamsFilter (type) {
      return isConfParamsMap[type]?.text ?? '—'
    }
  },
  created () {
    this.btnsPurviewData = this.btnsPurviewMap[this.$route.meta.permission[0]]
  },
  computed: {},
  methods: {
    /**
     * 跳转到配置模板页面
     */
    _toConfigTemp (record) {
      console.log(record)
      this.$router.push(`/custContractManage/ConfigTemp/${record.templateNo}`)
    },
    /**
     * 修改模板
     */
    _editTemp (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    /**
     * 同步模板状态
     */
    _syncTempStatus (record) {
      syncTempStatus({})
        .then((res) => {
          this.$message.info('同步成功')
          if (res.syncNums > 0) {
            this.$refs.table.refresh()
          }
        })
        .catch(() => {})
    },
    /**
     * 切换searchBar展开/关闭name
     */
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    /**
     * 模板上下架
     */
    handleChangeShelves (record) {
      if (!record.isConfParams) {
        this.$message.warn('该模板未配置模板参数,暂不允许上架')
        return false
      }
      const params = { isUpShelf: record.isUpShelf === 1 ? 0 : 1, templateNo: record.templateNo }
      editShelves(params)
        .then((res) => {
          this.$refs.table.refresh()
          this.$message.info(`${record.isUpShelf === 1 ? '下架' : '上架'}成功`)
        })
        .catch((e) => {})
    },
    /**
     *  新建/修改模板
     */
    handleOk () {
      const form = this.$refs.createForm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 修改 e.g.
          updateTemp(values)
            .then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.info('修改成功')
            })
            .catch((e) => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    /**
     * 取消表单
     */
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
      const form = this.$refs.createForm.form
      form.resetFields() // 清理表单数据（可不做）
    }
  }
}
</script>
<style lang="less" scoped>
.iconUrl {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}
</style>
